<template>
  <div class="page-container">
    <a-tabs v-model:active-key="activeTabsKey" @change="tabsChangeFn">
      <!-- 配置了短长租业务才显示对应的长短租选项 -->
      <a-tab-pane :key="1" title="自驾短租" />
      <a-tab-pane :key="2" title="自驾长租" />
    </a-tabs>
    <div class="price-config-wrapper">
      <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" />
      <table-index :table="table" @loadData="loadData">
        <template #table-summary>
          <div class="table-summary-box">
            <a-alert>
              <template #icon>
                <icon-exclamation-circle style="color: #165dff" />
              </template>
              声明：系统预制的模板仅作参考，请根据商户的实际场景调整合同模板中的内容，北京妙橙网络科技有限公司将不承担合同的任何保证
            </a-alert>
          </div>
        </template>
        <!-- 模版名称 -->
        <template #templateName="{ record }">
          <a-tooltip :content="getTooltipFn(record)" :disabled="record.isSysTemplate !== 0">
            {{ record.templateName }}<icon-question-circle v-if="record.isSysTemplate == 0" style="color: #165dff" />
          </a-tooltip>
        </template>
        <template #siteNameList="{ record }">
          <span class="site-num-val" v-if="record.isSysTemplate == 0">全部门店</span>
          <span class="site-num-val" v-else-if="record.siteNameList && record.siteNameList.length">
            {{ record.siteNameList.length }}
          </span>
          <a-button
            v-if="record.siteNameList && record.siteNameList.length"
            type="outline"
            size="mini"
            class="view-btn"
            @click="viewSiteListFn(record)"
          >
            查看
          </a-button>
        </template>
        <!-- 状态 -->
        <template #templateStateName="{ record }">
          <div class="flex items-center status-wrapper">
            <span :class="[record.templateState === 1 ? 'close' : 'open', 'status-icon']"></span>
            <span>{{ record.templateStateName }}</span>
          </div>
        </template>
      </table-index>
    </div>
  </div>

  <!-- 配置门店 -->
  <a-modal
    v-model:visible="siteNameVisible"
    @close="onClose"
    @before-ok="onConfirm"
    @before-open="getSiteListFn"
    title="应用门店"
    :mask-closable="false"
    class="modal-dialog-wrapper"
    unmount-on-close
    width="45vw"
  >
    <fast-transfer style="width: 100%" v-model="currentRecord.siteIdList" :selectedList="selectedList" :data-source="siteList" />
  </a-modal>

  <!-- 门店详情 -->
  <TemplateSiteModal ref="templateSiteModalRef" />

  <!-- 预览合同模板 -->
  <HTMLModal v-model="htmlVisible" :title="htmlTitle" :htmlString="htmlString" />
</template>

<script setup lang="ts" name="ContractTemplateList">
  import { ref, computed, reactive, onMounted } from 'vue'
  import { useFetchTableDataApi, useTable } from '@/hooks/table'
  import { cloneDeep } from 'lodash-es'
  import {
    getContractTemplateList,
    addContractStore,
    changeContractTemplateStatus,
    getContractStoreList,
    getContractTemplateStore,
    previewContractTemplate,
  } from '@/api/business/contract'
  import useNavigate from '@/hooks/useNavigate'
  import { usePageDict } from '@/hooks/useDict'
  import { Message, Modal } from '@arco-design/web-vue'
  import TemplateSiteModal from './components/template-site-modal.vue'
  import HTMLModal from './components/html-modal.vue'

  const { navigateTo } = useNavigate()
  const siteModalLoading = ref(false)
  const siteNameVisible = ref(false)
  // 默认短租
  const activeTabsKey = ref(1)
  const queryParam = reactive<any>({
    orderType: 1,
  })

  const dict = usePageDict('contractPageData')
  const searchList = computed(() => {
    return [
      { label: '模板名称', prop: 'templateNameLike', type: 'a-input', maxlength: 20 },
      {
        label: '应用门店',
        prop: 'siteId',
        type: 'remote-select',
        attrs: {
          type: 'site_listBystaff',
        },
      },
      {
        label: '合同类型',
        prop: 'contractType',
        type: 'a-select',
        options: dict.contractTypeEnum,
      },
      {
        label: '客户类型',
        prop: 'clientType',
        type: 'a-select',
        options: dict.clientTypeEnum,
      },
      {
        label: '状态',
        prop: 'templateState',
        type: 'a-select',
        options: dict.templateStateEnum,
      },
    ]
  })

  const currentRecord = ref<any>()
  const table = useTable({
    columns: [
      { title: '模板名称', dataIndex: 'templateName', slotName: 'templateName', fixed: 'left', width: 240 },
      { title: '合同类型', dataIndex: 'contractTypeName', width: 100 },
      { title: '客户类型', dataIndex: 'clientTypeName', width: 100 },
      { title: '应用门店', dataIndex: 'siteNameList', slotName: 'siteNameList', width: 150 },
      { title: '状态', dataIndex: 'templateStateName', slotName: 'templateStateName', width: 80 },
      { title: '备注', dataIndex: 'remark', ellipsis: true },
      { title: '操作人', dataIndex: 'updateUserName', width: 100 },
      { title: '操作时间', dataIndex: 'updateTime', width: 170 },
    ],
    operates: [
      {
        label: '预览模版',
        permission: 'svms:business:contract:template.preview',
        method: (record: any) => onTemplatePreview(record),
      },
      {
        label: '详情',
        permission: 'svms:business:contract:template.detail',
        method: (record: any) => {
          navigateTo(`/contract/template/detail/${record.id}?orderType=${queryParam.orderType}`, `${record.templateName}-合同模板详情`)
        },
      },
      {
        label: '编辑',
        permission: 'svms:business:contract:template.edit',
        method: (record: any) => {
          navigateTo(`/contract/template/edit/${record.id}?orderType=${queryParam.orderType}`, `${record.templateName}-编辑合同模板`)
        },
      },
      {
        label: '应用门店',
        permission: 'svms:business:contract:template.apply',
        show: (record: any) => record.isSysTemplate !== 0,
        method: (record: any) => {
          currentRecord.value = cloneDeep(record)
          siteNameVisible.value = true
        },
      },
      {
        label: '启用',
        permission: 'svms:business:contract:template.enable',
        show: (record: any) => record.templateState === 1 && record.isSysTemplate !== 0,
        method: (record: any) => {
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            content: `请确认是否启用？`,
            onOk: () => {
              changeContractTemplateStatus({ id: record.id, templateState: 0 }).then((res: any) => {
                console.log(res, 'res')
                loadData()
              })
            },
          })
        },
      },
      {
        label: '停用',
        permission: 'svms:business:contract:template.disable',
        show: (record: any) => record.templateState === 0 && record.isSysTemplate !== 0,
        method: (record: any) => {
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            content: `停用模板会清空该模板关联的应用门店，请确认是否停用？`,
            onOk: () => {
              changeContractTemplateStatus({ id: record.id, templateState: 1 }).then((res: any) => {
                console.log(res, 'res')
                loadData()
              })
            },
          })
        },
      },
    ],
    buttons: [
      {
        type: 'primary',
        icon: 'plus',
        label: '新增',
        permission: 'svms:business:contract:template.create',
        method: () => {
          navigateTo(
            `/contract/template/create?orderType=${queryParam.orderType}`,
            `${queryParam.orderType == 1 ? '新增短租合同模板' : '新增长租合同模板'}`
          )
        },
      },
    ],
  })

  const getTooltipFn = (record: any) => {
    const { contractTypeName, clientTypeName } = record
    return `除系统模板外，门店未关联其他${contractTypeName}模板的${clientTypeName}的订单，以系统模板作为生成${record.contractTypeName}的依据`
  }

  const tabsChangeFn = (val: string | number) => {
    // 清空 查询条件 开始
    for (var k in queryParam) {
      queryParam[k] = undefined
    }
    queryParam.orderType = val
    // 清空 查询条件 结束
    loadData(1)
  }

  // 查看门店列表弹窗
  const templateSiteModalRef = ref()
  const viewSiteListFn = (record: any) => {
    templateSiteModalRef.value.open(record, getContractTemplateStore)
  }

  // 应用门店 begin
  const onClose = () => {
    siteNameVisible.value = false
    siteModalLoading.value = false
    currentRecord.value.siteIdList = []
  }
  const onConfirm = async () => {
    await new Promise<void>((resolve, reject) => {
      if (!currentRecord.value.siteIdList || currentRecord.value.siteIdList.length === 0) {
        Message.error('请选择门店')
        reject()
        return
      }
      addContractStore({ id: currentRecord.value.id, siteIdList: currentRecord.value.siteIdList })
        .then(() => {
          Message.success('应用成功')
          siteNameVisible.value = false
          loadData()
          resolve()
        })
        .catch((error: any) => {
          Message.error(error.message)
          reject()
        })
    })
  }

  const selectedList = ref([])
  const siteList = ref([])
  const getSiteListFn = async () => {
    const res = await getContractStoreList({
      contractType: currentRecord.value.contractType,
      clientType: currentRecord.value.clientType,
      orderType: queryParam.orderType,
      id: currentRecord.value.id,
    })
    siteList.value = res.result.map((item: any) => {
      return {
        label: item.siteName,
        value: item.id,
      }
    })
    selectedList.value = []
  }
  // 应用门店 end

  // 预览模版 begin
  const htmlTitle = ref('')
  const htmlString = ref('')
  const htmlVisible = ref(false)
  const onTemplatePreview = (record: any) => {
    previewContractTemplate({
      id: record.id,
      orderType: queryParam.orderType,
    }).then((res: any) => {
      console.log(res, 'res')
      htmlTitle.value = `${res.result.templateName}模板预览`
      htmlString.value = res.result.contractContent
      htmlVisible.value = true
    })
  }
  // 预览模版 end

  const loadData = useFetchTableDataApi(table, queryParam, getContractTemplateList)

  onMounted(() => {
    loadData()
  })
</script>

<style lang="less" scoped>
  .page-container {
    .price-config-wrapper {
      .table-summary-box {
        width: 100%;
        margin-right: 10px;
      }

      .site-num-val {
        margin-right: 6px;
      }
    }
  }

  .status-wrapper {
    height: 28px;
    .status-icon {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin-right: 8px;
      &.open {
        background: #00b42a;
      }
      &.close {
        background: #ea0000;
      }
    }
  }

  .pop-orgs {
    max-width: 760px;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    div {
      background: #f2f3f5;
      margin-right: 10px;
      margin-bottom: 10px;
      padding: 2px 6px;
      border-radius: 2px;
      color: #1d2129;
      word-break: break-all;
    }
  }
</style>
